package com.dove.kuaizishareas.wificonnection;

import java.util.ArrayList;
import java.util.List;

import com.dove.kuaizishareas.R;
import com.dove.kuaizishareas.utils.WifiHotUtil;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class WifiStart extends Activity {

	private static final int OPEN = 1;
	private static final int SERVEROPEN = 2;
	private static final int MODIFYOPEN = 3;
	private WifiManager mWifiManager;
	private WifiInfo mWifiInfo;
	private TextView usernametext = null;
	
	private WifiHotUtil wifiHotUtil;
	private final String defaultHotName = "yukunjin-Hot";
	private final String defaultHotPwd = "12345678";
	private List<ScanResult> wifiList;
	private boolean isConnected = false;
	private List<String> passableHotsPot;
	private WifiReceiver wifiReceiver;
	private Context mContext;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.wifistart); // 设置当前屏幕
		mContext = this;

		mWifiManager = (WifiManager) this.getApplicationContext()
				.getSystemService(Context.WIFI_SERVICE);

		mWifiInfo = mWifiManager.getConnectionInfo();
		String ip = intToIp(mWifiInfo.getIpAddress());

		usernametext = (TextView) findViewById(R.id.username);
		usernametext.setText(Build.MODEL);

		Toast.makeText(WifiStart.this, ip, Toast.LENGTH_SHORT).show();

	}

	/************** 点击了“发送Wifi文件” ***************/
	public void StartButton(View view) {
		initWifiHot();//初始化创建热点
//		if (mWifiManager.isWifiEnabled()) {
//            mWifiManager.setWifiEnabled(false);
//        }
//		if(wifiHotUtil==null){
//			wifiHotUtil = new WifiHotUtil(mContext);
//		}
//		wifiHotUtil.closeWifiAp();
//		initConnectWifiHot();//初始化热点连接
//		if (mWifiManager.getWifiState() != WifiManager.WIFI_STATE_ENABLED) {
//			showDialog(OPEN);// 调用onCreateDialog
//		} else {
//			Intent i = new Intent(WifiStart.this, WifiUserList.class);
//			// Intent i = new Intent(WifiStart.this, choosecontactlocal.class);
//			i.putExtra("username", usernametext.getText().toString());
//			startActivity(i);
//		}
	}

	/*
	 * author:yukunjin
	 * 初始化WiFi热点创建
	 */
	private void initWifiHot() {
		//init WifiHotUtil
		wifiHotUtil = new WifiHotUtil(mContext);
		wifiHotUtil.startWifiAp(defaultHotName, defaultHotPwd);
		Intent i = new Intent(WifiStart.this,
				WifiUserList.class);
		i.putExtra("username", usernametext.getText().toString());
		startActivity(i);
	}

	/************** 点击了“接收Wifi文件” ***************/
	public void ReceiveButton(View view) {
//		initWifiHot();//初始化热点创建
		if (mWifiManager.isWifiEnabled()) {
			mWifiManager.setWifiEnabled(false);
		}
		if(wifiHotUtil==null){
			wifiHotUtil = new WifiHotUtil(mContext);
		}
		wifiHotUtil.closeWifiAp();
		initConnectWifiHot();//初始化热点连接
//		if (mWifiManager.getWifiState() != WifiManager.WIFI_STATE_ENABLED) {
//			showDialog(SERVEROPEN);// 调用onCreateDialog
//		} else {
//			Intent intent = new Intent(WifiStart.this, WifiReceive.class);
//			intent.putExtra("username", usernametext.getText().toString());
//			startActivity(intent);
//		}

	}
	/*
	 * author:yukunjin
	 * 初始化WiFi热点连接
	 */
	private void initConnectWifiHot() {
		mWifiManager.setWifiEnabled(true);
		wifiReceiver = new WifiReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
		filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
		filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
		registerReceiver(wifiReceiver, filter);
		mWifiManager.startScan();
//		wifiList = mWifiManager.getScanResults();
//		onReceiveNewNetworks(wifiList);
	}
	/*
	 * author:yukunjin
	 * 监听热点变化
	 */
	private final class WifiReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			wifiList = mWifiManager.getScanResults();
			if (wifiList == null || wifiList.size() == 0 || isConnected)
				return;
			onReceiveNewNetworks(wifiList);
		}
	}
	/*
	 * author:yukunjin
	 * 当搜索到新的wifi热点时判断该热点是否符合规格
	 */
	public void onReceiveNewNetworks(List<ScanResult> wifiList){
		Log.i("dove", "wifistart:onReceiveNewNetworks:"+wifiList.size());
		passableHotsPot = new ArrayList<String>();
		for(ScanResult result:wifiList){
			if((result.SSID).equals(defaultHotName)){
				passableHotsPot.add(result.SSID);
				Log.i("dove", "passableHotsPot:"+result.SSID);
			}
		}
		synchronized (this) {
			connectToHotpot();
		}
	}
	/*
	 * author:yukunijin
	 * 连接到热点
	 */
	public void connectToHotpot(){
		if(passableHotsPot==null || passableHotsPot.size()==0)
			return;
		WifiConfiguration wifiConfig = this.setWifiParams(passableHotsPot.get(0));
		int wcgID = mWifiManager.addNetwork(wifiConfig);
		boolean flag = mWifiManager.enableNetwork(wcgID, true);
		isConnected = flag;
		if(flag){
			//销毁时注销广播
			if(wifiReceiver!=null){
				unregisterReceiver(wifiReceiver);
			}
			Intent i = new Intent(WifiStart.this,
					WifiReceive.class);
			i.putExtra("username", usernametext.getText().toString());
			startActivity(i);
		}
		Log.i("dove", "connect success? "+flag);
	}
	/*
	 * author:yukunjin
	 * 设置要连接的热点的参数
	 */
	public WifiConfiguration setWifiParams(String ssid){
		WifiConfiguration apConfig=new WifiConfiguration();
		apConfig.SSID="\""+ssid+"\"";
		apConfig.preSharedKey="\""+defaultHotPwd+"\"";
//        apConfig.SSID=ssid;
//        apConfig.preSharedKey = defaultHotPwd;
		apConfig.hiddenSSID = true;
		apConfig.status = WifiConfiguration.Status.ENABLED;
//        apConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
		apConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
		apConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
		apConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
		apConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
		apConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
		apConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
		apConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
		return apConfig;
	}

	/************** 点击了“修改您的用户名” ***************/
	public void ModifyButton(View view) {

		showDialog(MODIFYOPEN);// 调用onCreateDialog
	}

	/************** 提示是否打开Wifi提示框 ***************/
	protected Dialog onCreateDialog(int id) {
		switch (id) {
			case OPEN:
				return new AlertDialog.Builder(WifiStart.this).setTitle("温馨提示")
						.setMessage("您的WiFi处于关闭状态，是否打开？").setIcon(
								android.R.drawable.ic_dialog_info)
						.setPositiveButton("打开", new OnClickListener() {

							public void onClick(DialogInterface dialog, int which) {

								mWifiManager.setWifiEnabled(true);
								Toast.makeText(WifiStart.this, "已为您启动WiFi服务",
										Toast.LENGTH_SHORT).show();

								Intent i = new Intent(WifiStart.this,
										WifiUserList.class);
								startActivity(i);

							}
						}).setNegativeButton("取消", new OnClickListener() {

							public void onClick(DialogInterface dialog, int which) {

								Toast.makeText(WifiStart.this, "您的WiFi服务未启动",
										Toast.LENGTH_SHORT).show();

							}
						}).create();
			case SERVEROPEN:
				return new AlertDialog.Builder(WifiStart.this).setTitle("温馨提示")
						.setMessage("您的WiFi处于关闭状态，是否打开？").setIcon(
								android.R.drawable.ic_dialog_info)
						.setPositiveButton("打开", new OnClickListener() {

							public void onClick(DialogInterface dialog, int which) {

								mWifiManager.setWifiEnabled(true);
								Toast.makeText(WifiStart.this, "已为您启动WiFi服务",
										Toast.LENGTH_SHORT).show();

								Intent i = new Intent(WifiStart.this,
										WifiReceive.class);
								startActivity(i);

							}
						}).setNegativeButton("取消", new OnClickListener() {

							public void onClick(DialogInterface dialog, int which) {

								Toast.makeText(WifiStart.this, "您的WiFi服务未启动",
										Toast.LENGTH_SHORT).show();

							}
						}).create();
			case MODIFYOPEN:
				// 新建一个编辑框，默认显示设备名称+"_"
				final EditText deviceTypeEdit = new EditText(this);
				deviceTypeEdit.setText(Build.MODEL);
				// 把光标定位到最后一个字符后面
				deviceTypeEdit.setSelection(Build.MODEL.length());
				// 弹出对话框要求用户输入设备型号或标识
				new AlertDialog.Builder(this).setTitle("请输入设备型号或标识：").setView(
						deviceTypeEdit).setPositiveButton("确定",
						new DialogInterface.OnClickListener() {

							public void onClick(DialogInterface dialog, int which) {
								// 获取用户输入后的设备类型
								String devicetype = deviceTypeEdit.getText()
										.toString().trim();
								usernametext.setText(devicetype);

							}
						}).setNegativeButton("取消", null).show();
			default:
				return null;
		}
	}

	private String intToIp(int i) {
		return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF)
				+ "." + ((i >> 24) & 0xFF);
	}

	@Override
	public void onBackPressed() {
		//关闭热点
		Log.i("dove", "wifistart:onBackPressed-热点已关闭");
		if(wifiHotUtil==null){
			wifiHotUtil = new WifiHotUtil(mContext);
		}
		wifiHotUtil.closeWifiAp();
		// TODO Auto-generated method stub
		super.onBackPressed();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		//关闭热点
		if(wifiHotUtil==null){
			wifiHotUtil = new WifiHotUtil(mContext);
		}
		wifiHotUtil.closeWifiAp();
		Log.i("dove", "wifistart:onDestroy-热点已关闭");
		super.onDestroy();
	}

}
